﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.TownHall.ServiceClient;
using NASA.BeAMartian.Model;

namespace NASA.BeAMartian.Views.Learn
{
    public partial class AskQuestionPage : PhoneApplicationPage
    {
        public THServiceClient client = new THServiceClient();
        ClientState _clientState = new ClientState();
        public AskQuestionPage()
        {
            InitializeComponent();

            FrameworkElement _root = Application.Current.RootVisual as FrameworkElement;
            _clientState = (ClientState)_root.DataContext;

            tbPageTitle.Text = String.Format("TOPIC: {0}", _clientState.CurrentTopic.Name.ToUpper());

            client.QuestionPosted += new QuestionPostedEventHandler(client_QuestionPosted);
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Learn/QuestionListPage.xaml", UriKind.Relative));
        }

        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            if (ApplicationContext.Instance.UserData == null)
                NavigationService.Navigate(new Uri("/Views/SignIn.xaml?return=question", UriKind.Relative));
            else
            {
                client.PostQuestion(_clientState.CurrentTopic.Slug, tbQuestion.Text, tbQuestionTags.Text);
            }
        }

        void client_QuestionPosted(object sender, QuestionPostedEventArgs e)
        {
            Action<Nugget> act = new Action<Nugget>(postQuestion);
            this.Dispatcher.BeginInvoke(act, e.Question);
        }

        void postQuestion(Nugget body)
        {
            NavigationService.Navigate(new Uri("/Views/Learn/QuestionListPage.xaml", UriKind.Relative));            
        }
    }
}